import SchemaForm from '@/components/SchemaForm';
import { model, schema } from '@/ts/base';
import { IDirectory } from '@/ts/core';
import { ProFormColumnsType } from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import UploadItem from '../../tools/uploadItem';
import { EntityColumns } from './entityColumns';
import { ProFormInstance } from '@ant-design/pro-form';
import {
  IBaseModel,
  IModelManager,
  Protocol,
  SupportedProtocols,
} from '@/ts/core/chat/agent/aiModel';

interface IProps {
  formType: string;
  typeName: string;
  current: IModelManager | IBaseModel;
  finished: () => void;
}

/*
  大模型表单
*/
const ModelForm = (props: IProps) => {
  let title = '';
  const readonly = props.formType === 'remark';
  let directory: IDirectory;
  let initialValue: any;
  let manager: IModelManager;
  const formRef = useRef<ProFormInstance>();
  switch (props.formType) {
    case 'newModel':
      directory = (props.current as IModelManager).target.directory;
      title = '新建' + props.typeName;
      initialValue = {};
      manager = props.current as IModelManager;
      break;
    case 'updateModel':
      directory = (props.current as IBaseModel).directory;
      title = '更新' + props.typeName;
      initialValue = (props.current as IBaseModel).metadata;
      manager = (props.current as IBaseModel).modelManager;
      break;
    case 'copyModel':
      directory = (props.current as IBaseModel).directory;
      title = '更新' + props.typeName;
      initialValue = { ...(props.current as IBaseModel).metadata, id: undefined };
      manager = (props.current as IBaseModel).modelManager;
      break;
    case 'remark':
      directory = (props.current as IBaseModel).directory;
      title = '查看' + props.typeName;
      initialValue = (props.current as IBaseModel).metadata;
      manager = (props.current as IBaseModel).modelManager;
      break;
    default:
      return <></>;
  }

  const getColumns = (options: model.BaseModel[]) => {
    const columns: ProFormColumnsType<schema.XModel>[] = [
      {
        title: '图标',
        dataIndex: 'icon',
        colProps: { span: 24 },
        renderFormItem: (_, __, form) => {
          return (
            <UploadItem
              readonly={readonly}
              typeName={props.typeName}
              icon={initialValue.icon}
              onChanged={(icon) => {
                form.setFieldValue('icon', icon);
              }}
              directory={directory}
            />
          );
        },
      },
      {
        title: '已支持协议',
        dataIndex: 'protocol',
        valueType: 'select',
        colProps: {
          span: 24,
        },
        formItemProps: {
          rules: [{ required: true, message: '模型名称为必填项' }],
        },
        fieldProps: {
          options: Object.entries(Protocol).map(([key, value]) => {
            return { label: `${key}（${value}）`, value: key };
          }),
        },
      },
      {
        title: '请求签名（ApiKey）',
        dataIndex: 'apiKey',
        valueType: 'password',
        colProps: { span: 24 },
        readonly,
        formItemProps: {
          rules: [{ required: true, message: '模型名称为必填项' }],
        },
      },
      {
        title: '模型名称',
        dataIndex: 'code',
        readonly,
        valueType: 'select',
        colProps: { span: 24 },
        fieldProps: {
          options: options.map((item) => {
            return { label: item.id, value: item.id };
          }),
        },
        formItemProps: {
          rules: [{ required: true, message: '模型名称为必填项' }],
        },
      },
    ];
    if (readonly) {
      columns.push(...EntityColumns(initialValue));
    }
    columns.push({
      title: '备注信息',
      dataIndex: 'remark',
      valueType: 'textarea',
      colProps: { span: 24 },
      readonly: readonly,
      formItemProps: {
        rules: [{ required: true, message: '备注信息为必填项' }],
      },
    });
    return columns;
  };
  const [columns, setColumns] = useState(getColumns([]));

  const loadModels = async (protocol: string, apiKey: string) => {
    if (apiKey) {
      switch (protocol) {
        case 'Silicon':
        case 'Orginone': {
          const models = await manager.getModels(protocol, apiKey);
          setColumns(getColumns(models));
          break;
        }
      }
    }
  };

  useEffect(() => {
    loadModels(initialValue.protocol, initialValue.apiKey);
  }, []);

  return (
    <SchemaForm<schema.XModel>
      formRef={formRef}
      open
      title={title}
      width={640}
      columns={columns}
      initialValues={initialValue}
      rowProps={{
        gutter: [24, 0],
      }}
      layoutType="ModalForm"
      onOpenChange={(open: boolean) => {
        if (!open) {
          props.finished();
        }
      }}
      onValuesChange={async (_: schema.XModel, values: schema.XModel) => {
        loadModels(values.protocol, values.apiKey);
      }}
      onFinish={async (values) => {
        switch (props.formType) {
          case 'updateModel':
            await (props.current as IBaseModel).update({
              ...initialValue,
              ...values,
            });
            break;
          case 'copyModel':
            await (props.current as IBaseModel).modelManager.createModel({
              ...values,
            });
            break;
          case 'newModel':
            await (props.current as IModelManager).createModel({
              ...values,
            });
            break;
        }
        props.finished();
      }}
    />
  );
};

export default ModelForm;
